package com.magicodex.bookkeeping.biz.common.util;

import com.magicodex.bookkeeping.biz.common.constant.DateConstants;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 日期工具类。
 * </p>
 *
 * @author mh.z
 */
public class DateUtil {

    private static final DateTimeFormatter YEAR_DAY_FORMATTER;
    private static final DateTimeFormatter YEAR_SECOND_FORMATTER;

    static {
        YEAR_DAY_FORMATTER = DateTimeFormatter.ofPattern(DateConstants.YEAR_DAY);
        YEAR_SECOND_FORMATTER = DateTimeFormatter.ofPattern(DateConstants.YEAR_SECOND);
    }

    /**
     * 格式化日期成字符串，格式是yyyy-MM-dd HH:mm:ss
     *
     * @param zonedDateTime
     * @return
     */
    public static String formatYearSecond(ZonedDateTime zonedDateTime) {
        if (zonedDateTime == null) {
            return null;
        }

        return YEAR_SECOND_FORMATTER.format(zonedDateTime);
    }

    /**
     * 解析成日期，格式是yyyy-MM-dd HH:mm:ss
     *
     * @param text
     * @return
     */
    public static ZonedDateTime parseYearSecond(String text) {
        ZonedDateTime zonedDateTime = null;

        if (StringUtil.isNotEmpty(text)) {
            LocalDateTime localDateTime = LocalDateTime.parse(text, YEAR_SECOND_FORMATTER);
            zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        }

        return zonedDateTime;
    }

    /**
     * 格式化日期成字符串，格式是yyyy-MM-dd
     *
     * @param zonedDateTime
     * @return
     */
    public static String formatYearDay(ZonedDateTime zonedDateTime) {
        if (zonedDateTime == null) {
            return null;
        }

        return YEAR_DAY_FORMATTER.format(zonedDateTime);
    }

    /**
     * 解析成日期，格式是yyyy-MM-dd
     *
     * @param text
     * @return
     */
    public static ZonedDateTime parseYearDay(String text) {
        ZonedDateTime zonedDateTime = null;

        if (StringUtil.isNotEmpty(text)) {
            LocalDate localDate = LocalDate.parse(text, YEAR_DAY_FORMATTER);
            zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        }

        return zonedDateTime;
    }

}
